<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;

class WxController extends Controller{
  //appid
  protected $appID = "wxbc5c9f362b1265ef";
  //appsecret
  protected $appsecret = "10c929c63ea359c10f75c154df2810c6";

  //获取微信的access_token
  public function getwxToken()
  {
    $wxurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appID."&secret=".$this->appsecret;
    $wx_timestamp = Redis::get('wx_timestamp');
    if(!isset($wx_timestamp) || (time()-$wx_timestamp>7200))
    {
      $json = file_get_contents($wxurl);
      $accessToken = json_decode($json);
      $access_token = $accessToken->access_token;
      $timestamp = time();
      Redis::set('wx_token',$access_token);
      Redis::set('wx_timestamp',$timestamp);
    }
    $wx_token = Redis::get('wx_token');
    return $wx_token;
  }

  //在微信中创建菜单
  public function createMenu()
  {
    $access_token = $this->getwxToken();
    $wxmenuapi = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
    $data = '{
                  "button": [
                      {
                          "name": "周年活动",
                          "sub_button": [
                              {
                                  "type": "view",
                                  "name": "问卷领奖",
                                  "url": "http://www.baidu.com"
                              },
                              {
                                  "type": "view",
                                  "name": "领卡券",
                                  "url": "http://weixin.qq.com/q/02hPmxIoJEdZk1_09Bhp4T"
                              }
                          ]
                      },
                      {
                          "type": "view",
                          "name": "领会员卡",
                          "url": "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQGl8TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAydEtldEppSkVkWmsxTTY0N05yNEUAAgSG0OVZAwSAM_EB"
                      }
                  ]
              }';
      //使用curl进行post请求
      $res = $this->curl_request($wxmenuapi,'post',$data);
      echo $res;
  }

//封装一个curl请求函数
//@url  请求地址
//@type 请求方式
//@data post请求携带的数据
  protected function curl_request($url,$type="post",$data="")
  {
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
    curl_setopt($ch,CURLOPT_HEADER, 0);

    $type = strtolower($type);
    switch($type){
      case 'get':
          break;
      case 'post':
          curl_setopt($ch, CURLOPT_POST, 1);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
          break;
    }
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
  }

  //获取openid
  //@code 从wx回调地址中获取到的code值,是获取特殊access_token的重要参数
  public function getOpenId($code)
  {
    $api_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appID&secret=$this->appsecret&code=$code&grant_type=authorization_code";
    $json = file_get_contents($api_url);
    $obj = json_decode($json);
    $openid = $obj->openid;
    $access_token = $obj->access_token;
    return $openid;
  }

  //创建会员卡
  public function createMembershipCard()
  {
    $access_token = $this->getwxToken();
    $wxcreateMemApi = "https://api.weixin.qq.com/card/create?access_token=".$access_token;
    $data = '{
            "card": {
                "card_type": "MEMBER_CARD",
                "member_card": {
                    "background_pic_url": "https://mmbiz.qlogo.cn/mmbiz/",
                    "base_info": {
                        "logo_url": "http://mmbiz.qpic.cn/mmbiz/iaL1LJM1mF9aRKPZ/0",
                        "brand_name": "不去科技",
                        "code_type": "CODE_TYPE_TEXT",
                        "title": "不去联盟会员卡",
                        "color": "Color010",
                        "notice": "使用时向服务员出示此券",
                        "service_phone": "020-88888888",
                        "description": "不可与其他优惠同享",
                        "date_info": {
                            "type": "DATE_TYPE_PERMANENT"
                        },
                        "sku": {
                            "quantity": 50000000
                        },
                        "get_limit": 3,
                        "use_custom_code": false,
                        "can_give_friend": true,
                        "location_id_list": [
                            123,
                            12321
                        ],
                        "custom_url_name": "立即使用",
                        "custom_url": "http://weixin.qq.com",
                        "custom_url_sub_title": "6个汉字tips",
                        "promotion_url_name": "营销入口1",
                        "promotion_url": "http://www.qq.com",
                        "need_push_on_view": true
                    },
                     "advanced_info": {
                       "use_condition": {
                           "accept_category": "鞋类",
                           "reject_category": "阿迪达斯",
                           "can_use_with_other_discount": true
                       },
                     "abstract": {
                           "abstract": "微信餐厅推出多种新季菜品，期待您的光临",
                           "icon_url_list": [
                               "http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sj  piby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0"
                           ]
                       },
                       "text_image_list": [
                           {
                               "image_url": "http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sjpiby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0",
                               "text": "此菜品精选食材，以独特的烹饪方法，最大程度地刺激食 客的味蕾"
                           },
                           {
                               "image_url": "http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sj piby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0",
                               "text": "此菜品迎合大众口味，老少皆宜，营养均衡"
                           }
                       ],
                       "time_limit": [
                           {
                               "type": "MONDAY",
                               "begin_hour":0,
                               "end_hour":10,
                               "begin_minute":10,
                               "end_minute":59
                           },
                           {
                               "type": "HOLIDAY"
                           }
                       ],
                       "business_service": [
                           "BIZ_SERVICE_FREE_WIFI",
                           "BIZ_SERVICE_WITH_PET",
                           "BIZ_SERVICE_FREE_PARK",
                           "BIZ_SERVICE_DELIVER"
                       ]
                   },
                    "supply_bonus": true,
                    "supply_balance": false,
                    "prerogative": "test_prerogative",
                    "auto_activate": true,
                    "custom_field1": {
                        "name_type": "FIELD_NAME_TYPE_LEVEL",
                        "url": "http://www.qq.com"
                    },
                    "activate_url": "http://www.qq.com",
                    "custom_cell1": {
                        "name": "使用入口2",
                        "tips": "激活后显示",
                        "url": "http://www.xxx.com"
                    },
                    "bonus_rule": {
                        "cost_money_unit": 100,
                        "increase_bonus": 1,
                        "max_increase_bonus": 200,
                        "init_increase_bonus": 10,
                        "cost_bonus_unit": 5,
                        "reduce_money": 100,
                        "least_money_to_use_bonus": 1000,
                        "max_reduce_bonus": 50
                    },
                    "discount": 10
                }
            }
        }';
    $res = $this->curl_request($wxcreateMemApi,'post',$data);
    dump($res);
  }

  //获取会员卡二维码
  public function getMemQRcode(){
    $access_token = $this->getwxToken();
    $api = "https://api.weixin.qq.com/card/qrcode/create?access_token=".$access_token;
    $data = ' {
              "action_name": "QR_CARD",
              "action_info": {
              "card": {
              "card_id": "p7ah91E9z-eup1jN8DJZ9BJQHX9M",
              "code": "198374613512",
              "is_unique_code": false ,
              "outer_str":"00001"
                }
               }
              }';
   $res = $this->curl_request($api,'post',$data);
   $res = json_decode($res);
   dump($res);
  }

//设置会员卡测试白名单
  public function setwhitename()
  {
    $access_token = $this->getwxToken();
    $api = "https://api.weixin.qq.com/card/testwhitelist/set?access_token=".$access_token;
    $data =
    '{
      "openid": [
          "o7ah91HRwamntLmzRCsmYWqf9S6I"
                   ],                                                                                                                                                                 
      "username": [
          "Gatsby"
                    ]
     }';
     $res = $this->curl_request($api,'post',$data);
     dump($res);
  }

  //创建ticket(创建可以携带参数的二维码)
  public function createticket()
  {
    $access_token = $this->getwxToken();
    $api = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;
    $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": 00001}}}';
    $res = $this->curl_request($api,'post',$data);
    dump($res);
  }
}
